package com.zxy.fmmall.service.impl;

import com.auth0.jwt.JWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zxy.fmmall.dao.UsersMapper;
import com.zxy.fmmall.entity.Users;
import com.zxy.fmmall.service.UserService;
import com.zxy.fmmall.utils.Base64Utils;
import com.zxy.fmmall.utils.MD5Utils;
import com.zxy.fmmall.vo.ResultVo;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UsersMapper usersMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public ResultVo checkLogin(String name, String pwd) {
        // 1.根据账号查询用户信息
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", name);
        Users users = usersMapper.selectOneByExample(example);
        // 2.判断
        if (users == null) {
            return ResultVo.error().message("用户名不存在");
        } else {
            // 对输入密码进行加密
            String md5Pwd = MD5Utils.md5(pwd);
            // 使用加密后密码和user中密码进行比较
            if (md5Pwd.equals(users.getPassword())) {
                // 验证成功
                // 生成token

                HashMap<String, Object> map = new HashMap<>();
                map.put("key1", "value1");
                map.put("key2", "value2");

                JwtBuilder builder = Jwts.builder();
                String token = builder.setSubject(name) // 主题就是token中携带的数据
                        .setIssuedAt(new Date()) //设置token生成时间
                        .setId(users.getUserId().toString()) // 设置用户id位token id
                        .setClaims(map)
                        .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)) //设置过期时间
                        .signWith(SignatureAlgorithm.HS256, "zhangxueyang")  //设置加密方式和密码
                        .compact();

                //如果登录成功，将用户信息保存到redis中
                try {
                    stringRedisTemplate.boundValueOps(token).set(objectMapper.writeValueAsString(users));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }


                return ResultVo.ok().message("登陆成功").data("users", users).data("token", token);
            } else {
                // 密码错误
                return ResultVo.error().message("密码错误");
            }
        }

    }

    @Override
    @Transactional
    public ResultVo regist(String username, String password) {
        // 对一个对象加锁 因为spring中是单例的所以可以用直接用this
        synchronized (this) {
            // 1.根据用户查询，这个用户是否已经注册
            Example example = new Example(Users.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("username", username);
            List<Users> users = usersMapper.selectByExample(example);
            // 2.如果没注册进行注册
            if (users.size() == 0) {
                String md5Pwd = MD5Utils.md5(password);
                Users user = new Users();
                user.setUsername(username);
                user.setPassword(md5Pwd);
                user.setUserImg("img/default.png");
                user.setUserRegtime(new Date());
                user.setUserModtime(new Date());
                int res = usersMapper.insert(user);
                if (res > 0) {
                    return ResultVo.ok().message("注册成功");
                } else return ResultVo.error().message("注册失败");
            } else {
                return ResultVo.error().message("用户已经被注册");
            }
        }
    }

}
